import { isObject } from './utils';
/**
 * 深拷贝
 * @param {Object} obj 目标对象
 * @returns {Object} 深拷贝后的对象
 */
export function deepClone(obj) {
  if (!obj || typeof obj !== 'object') {
    return obj;
  }
  if (obj instanceof RegExp) {
    return obj;
  }
  const result = Array.isArray(obj) ? [] : {};
  Object.keys(obj).forEach((key) => {
    if (obj[key] && typeof obj[key] === 'object') {
      result[key] = deepClone(obj[key]);
    } else {
      result[key] = obj[key];
    }
  });
  return result;
}

/**
 * 弃用 -- 改用extend
 * 继承合并
 * @param {Object} destination 源
 * @param {Object} source 要合并的内容
 * @param {Boolean} overwrite 是否overwrite， 默认true，覆盖destination的值
 * @returns {Object} 合并后的对象
 */
export function mixin(destination, source, overwrite = true) {
  if (!isObject(destination)) {
    return source;
  }
  if (isObject(source)) {
    Object.keys(source).forEach((key) => {
      if (key in destination) {
        if (overwrite) {
          if (isObject(destination[key]) && isObject(source[key])) {
            mixin(destination[key], source[key], overwrite);
          } else {
            destination[key] = source[key];
          }
        }
      } else {
        destination[key] = source[key];
      }
    });
  }
  return destination;
}

// 弃用 -- 改用extend
export function mixins(target) {
  for (let i = 1; i < arguments.length; i++) {
    const source = arguments[i];
    mixin(target, source);
  }
  return target;
}

export const extend = Object.assign;
